package com.choco.jsondb.editor;

import com.choco.jsondb.Context;
import com.choco.jsondb.utils.FileUtil;
import com.choco.jsondb.utils.JSONUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class ArrayEditor implements Editor{

    private Map<String, ArrayList<String>> map;
    private Context context;

    public ArrayEditor(Context context) {
        map = new HashMap<>();
        this.context = context;
    }

    @Override
    public boolean put(String key, Object object){
        boolean result = false;

        if(object != null){
            result = insert(key, JSONUtil.getJsonString(object));
        }

        return result;
    }

    @Override
    public boolean put(String key, String jsonString) {
        boolean result = false;

        if(jsonString != null && jsonString.length() > 0) {
            result = insert(key, jsonString);
        }

        return result;
    }

    @Override
    public boolean put(Object object) {
        boolean result = false;

        if(object != null){
            result = insert(Context.DEFAULT_KEY, JSONUtil.getJsonString(object));
        }

        return result;
    }

    @Override
    public boolean put(String jsonString) {
        boolean result = false;

        if(jsonString != null && jsonString.length() > 0) {
            result = insert(Context.DEFAULT_KEY, jsonString);
        }

        return result;
    }

    private boolean insert(String key, String jsonStr){
        if(key == null || key.equals("")){
            key = Context.DEFAULT_KEY;
        }

        ArrayList<String> arrayList = map.get(key);
        if(arrayList == null){
            arrayList = new ArrayList<>();
        }
        arrayList.add(jsonStr);

        map.put(key, arrayList);

        return true;
    }

    @Override
    public boolean commit() {
        return FileUtil.write(context, map);
    }
}
